#!/bin/sh
#
# chkconfig: - 58 74
# description: memcached{{ item.port }} is the memcached daemon.
#

EXEC=/usr/bin/memcached
PIDFILE=/tmp/memcached{{ item.port }}.pid
PORT="{{ item.port }}"
HOST="{{ item.host }}"


case "$1" in
    start)
        if [ -f $PIDFILE ]; then
            echo "$PIDFILE exists, process is already running or crashed"
        else
            echo "Starting Memcached server..."
            $EXEC -d -m 32 -l $HOST -p $PORT -u root -P $PIDFILE
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]; then
            echo "$PIDFILE does not exist, process is not running"
        else
            PID=$(cat $PIDFILE)
            echo "Stopping ..."
            kill -9 $PID
            rm -f $PIDFILE
            echo "Memcached stopped"
        fi
        ;;
    status)
        if [ -f $PIDFILE ]; then
            PID=$(cat $PIDFILE)
            if [ ! -x /proc/${PID} ]; then
                echo 'Memcached is not running'
            else
                echo "Memcached is running ($PID)"
            fi
        else
            echo 'Memcached is not running'
        fi
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    *)
        echo "Please use start, stop, restart or status as first argument"
        ;;
esac
